package com.mhl.campuscabinet;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mhl.adapter.MsgAdapter;
import com.mhl.client.OkHttpUtils;
import com.mhl.entity.Msg;
import com.mhl.entity.Product;
import com.mhl.entity.User;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChatroomActivity extends AppCompatActivity implements View.OnClickListener{

    private List<Msg> msgList = new ArrayList<>();
    private EditText inputText;
    private Button send;
    private RecyclerView msgRecyclerView;
    private MsgAdapter adapter;
    private Socket socketSend;
    private String ip="192.168.31.115"; //修改
    private String port="6667";
    DataInputStream dis;
    DataOutputStream dos;
    boolean isRunning = false;
    //private TextView myName;
    private String recMsg;
    private boolean isSend=false;
    private int userId;
    private String id;
    private int providerId;


    private Handler handler = new Handler(Looper.myLooper()){//获取当前进程的Looper对象传给handler
        @Override
        public void handleMessage(@NonNull Message msg){//?
            if(!recMsg.isEmpty()){
                addNewMessage(recMsg,Msg.TYPE_RECEIVED);//添加新数据
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chatroom);
        Intent intent =getIntent();

        providerId = intent.getIntExtra("provider_id", 2);
        userId=intent.getIntExtra("user_id",1);
        inputText = findViewById(R.id.input_text);
        send=findViewById(R.id.send);
        send.setOnClickListener(this);

        //getHistory();
        //获取历史聊天记录
        JSONObject historyJson = new JSONObject();
        MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
        userId = User.getInstance().getUserId();
        //name = "1";//正式合并时更改
        try {
            //historyJson.put("provider_id",providerId);
            historyJson.put("user_id",userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String json = historyJson.toString();
        RequestBody requestBody = RequestBody.Companion.create(json, mediaType);
        //todo fill true ip02
        Log.e("ee","test");
        OkHttpUtils.sendOkHttpResponse("http://192.168.31.115:8000/api/chat/get", requestBody, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                System.out.println(e);
                Log.e("ee","afdafd");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                final String history = response.body().string();
                int type = Msg.TYPE_RECEIVED;
                try {
                    JSONObject itemsJson = new JSONObject(history);
                    JSONArray itemArray = itemsJson.getJSONArray("data");

                    for (int i = 0; i < itemArray.length(); i++) {
                        JSONObject item = itemArray.getJSONObject(i);
                        if (User.getInstance().getUserId() == (item.getInt("user_id"))){
                            type = Msg.TYPE_SENT;
                            System.out.println(type);
                        }

                        Msg msg = new Msg(item.getString("text"),type);
                        msgList.add(msg);
                    }

                    //System.out.println("更新UI");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                        }
                    });
                    //System.out.println("更新UI2");

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });



        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                LinearLayoutManager layoutManager = new LinearLayoutManager(ChatroomActivity.this);
                msgRecyclerView= findViewById(R.id.msg_recycler_view);
                msgRecyclerView.setLayoutManager(layoutManager);
                adapter = new MsgAdapter(msgList);
                msgRecyclerView.setAdapter(adapter);
                //getHistory();

            }
        });

        new Thread(new Runnable(){
            @Override
            public void run(){

                try{
                    if((socketSend = new Socket(ip,Integer.parseInt(port)))==null){
                        Log.d("ttw","发送了一条消息1");
                    }
                    else{
                        isRunning = true;
                        Log.d("ttw","发送了一条消息2");
                        dis = new DataInputStream(socketSend.getInputStream());
                        dos = new DataOutputStream(socketSend.getOutputStream());
                        //new Thread(new historyThread(),"历史记录线程").start();
                        new Thread(new receive(),"接收线程").start();
                        new Thread(new Send(),"发送线程").start();
                    }
                }catch(Exception e){
                    isRunning = false;
                    e.printStackTrace();
                    Looper.prepare();
//                    Toast.makeText(ChatroomActivity.this, "连接服务器失败！！！", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                    try{
                        socketSend.close();
                    }catch(IOException e1){
                        e1.printStackTrace();
                    }
                    finish();
                }
            }
        }).start();
    }

    public void addNewMessage(String msg,int type){
        Msg message = new Msg(msg,type);
        msgList.add(message);
        adapter.notifyItemInserted(msgList.size()-1);
        msgRecyclerView.scrollToPosition(msgList.size()-1);
    }

    class receive implements Runnable{
        public void run(){
            recMsg = "";
            while(isRunning){
                try{
                    recMsg = dis.readUTF();
                    Log.d("ttw","recMsg: "+ recMsg);
                }catch(Exception e){
                    e.printStackTrace();
                }
                if(!TextUtils.isEmpty(recMsg)){
                    Log.d("ttw","inputStream:"+dis);
                    Message message = new Message();
                    message.obj=recMsg;
                    handler.sendMessage(message);
                }
            }
        }
    }

    @Override
    public void onClick(View view){

        String content = inputText.getText().toString();
        @SuppressLint("SimpleDateFormat")
        String date = new SimpleDateFormat("hh:mm:ss").format(new Date());
        StringBuilder sb = new StringBuilder();
        sb.append(content).append("\n\n"+date);
        content = sb.toString();
        if(!"".equals(content)){
            Msg msg = new Msg(content,Msg.TYPE_SENT);
            msgList.add(msg);
            adapter.notifyItemInserted(msgList.size()-1);
            msgRecyclerView.scrollToPosition(msgList.size()-1);
            isSend = true;
        }
        sb.delete(0,sb.length());
    }

    class Send implements Runnable{
        @Override
        public void run(){

            while(isRunning){
                String content = inputText.getText().toString();
                //Log.d("ttw","发了一条消息");
                if(!"".equals(content)&&isSend){
                    @SuppressLint("SimpleDateFormat")
                    String date = new SimpleDateFormat("hh:mm:ss").format(new Date());
                    StringBuilder sb = new StringBuilder();

                    //name = "1";//正式合并时更改
                    userId = User.getInstance().getUserId();
                    sb.append(content).append("\n").append(userId).append("\n"+providerId);
                    System.out.println(userId);
                    content = sb.toString();
                    try{
                        dos.writeUTF(content);
                        //dos.writeUTF(name);
                        sb.delete(0,sb.length());
                        Log.d(String.valueOf(userId),"发送了一条消息");
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                    isSend = false;
                    inputText.setText("");
                }
            }
        }
    }
}

